package com.mgetwd.springbootweb.config;

import io.netty.util.internal.StringUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class RedisHelper {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private final static TimeUnit UNIT = TimeUnit.MINUTES;

    /**
     * put
     * @param key
     * @param value
     * @param timeout 单位秒
     */
    public void set(Object key,Object value,long timeout){
        redisTemplate.opsForValue().set("bif:" +key, value, timeout, UNIT);
    }

    public void set(Object key,Object value){
        redisTemplate.opsForValue().set("bif:" +key, value);
    }

    /**
     * get
     * @param key
     * @return
     */
    public Object get(Object key){
        return redisTemplate.opsForValue().get("bif:" +key);
    }

    /**
     * 设置key在固定时刻失效
     * @param key
     * @param date
     */
    public void key(Object key, Date date ){
        redisTemplate.expireAt("bif:" +key, date);
    }

    /**
     * 设置key在固定时刻失效
     * @param key
     * @param date
     */
    public void key(Object key, long time ){
        Date date = new Date(time);
        redisTemplate.expireAt("bif:" +key, date);
    }

    public boolean hasKey(Object key){
        return redisTemplate.hasKey("bif:" +key);
    }

    /**
     * 根据key删除
     * @param key
     * @return
     */
    public boolean delete(String key) {
        boolean flag=redisTemplate.delete("bif:" +key);
        return flag;
    }

    /**
     * 根据
     * @param key
     */
    public boolean checkResubmitKey(String key){
        if(StringUtil.isNullOrEmpty(key) && this.hasKey(key)) {
            this.delete(key);
            return true;
        }else {
            return false;
        }
    }

    /**
     * 设置key的生命周期
     *
     * @param key
     * @param time
     * @param timeUnit
     */
    public void expireKey(String key, long time, TimeUnit timeUnit) {
        redisTemplate.expire(key, time, timeUnit);
    }

    /**
     * 指定key在指定的日期过期
     *
     * @param key
     * @param date
     */
    public void expireKeyAt(String key, Date date) {
        redisTemplate.expireAt(key, date);
    }

    /**
     * 查询key的生命周期
     *
     * @param key
     * @param timeUnit
     * @return
     */
    public long getKeyExpire(String key, TimeUnit timeUnit) {
        return redisTemplate.getExpire(key, timeUnit);
    }

    /**
     * 将key设置为永久有效
     *
     * @param key
     */
    public void persistKey(String key) {
        redisTemplate.persist(key);
    }
}
